# mc_integral2.R
# Calculating a definite integral using the Monte Carlo method

# Exemplo de utilizacao:
# source('mc_integral2.R')
# mc_integral(sin, 0, pi)

# Rizzo pag 126

# NOTE: more efficient to calculate from 0 to b

mc_integrate <- function(rndgen_f, a, b, m=100000)
{
	# 1. Generate a random sample X1,...,Xm iid from the distribution of X
	X <- rndgen_f(m)

	# 2. For each observation Xi, compute
	# g(Xi) = I(Xi <= x) =
	# 		{ 1  Xi <= x
	# 		{ 0  Xi > x
	g <- (X < b)

	# 3. Compute F(x) = g.(X) = 1/m . sum[ I(Xi <= x) ]
	area <- 1/m * sum(g)

	if(a != 0)
		area <- area - mc_integral(rndgen_f, 0, a, m)
	area
}

# Minimum m to reduce variance to err standard error levels

min_var <- function(rndgen_f, a, b, m=5000, err=0.1)
{
	X <- rndgen_f(m)
	theta_error <- mean(X) - mean(Danos)
	theta_error / (err^2)
}

